package com.example.reacteui.register;


import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.reacteui.Login.Login;
import com.example.reacteui.R;
import com.example.reacteui.SQL.MyDatabaseHelper;


public class Register extends AppCompatActivity implements View.OnClickListener {

    private String username, password;

    private TextView toLogin;
    MyDatabaseHelper myDb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_register);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        findViewById(R.id.register).setOnClickListener(this);
        findViewById(R.id.toLogin).setOnClickListener(this);
        myDb = new MyDatabaseHelper(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.register:
                EditText usernameEditText = findViewById(R.id.username_register);
                EditText passwordEditText = findViewById(R.id.password_register);
                String username = usernameEditText.getText().toString();
                String password = passwordEditText.getText().toString();
                Log.d("TAG", "onCreate: username:" + username + "  password:" + password);
                Boolean isUsernameExists = myDb.checkUsername(username);
                if (isUsernameExists) {
                    Toast.makeText(this, "用户名已存在，请重新输入", Toast.LENGTH_SHORT).show();
                } else if (username.matches("^[a-zA-Z0-9]{8,15}$") && password.matches("^[0-9]{6}$")) {
                    boolean isInserted = myDb.insertData(username, password);
                    if (isInserted) {
                        Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(this, "用户名或密码格式不正确", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.toLogin:
                Intent intent = new Intent(Register.this, Login.class);
                startActivity(intent);

        }


    }
}
